
function GetQueryString(name){
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r!=null) return unescape(r[2]); return null;
}
function get_root_url(){
    return 'http://'+window.location.host;
}
function changeURLParam(url, ref, value)
{
    var str = "";
    if (url.indexOf('?') != -1)
        str = url.substr(url.indexOf('?') + 1);
    else
        return url + "?" + ref + "=" + value;
    var returnurl = "";
    var setparam = "";
    var arr;
    var modify = "0";

    if (str.indexOf('&') != -1) {
        arr = str.split('&');

        for (i in arr) {
            if (arr[i].split('=')[0] == ref) {
                setparam = value;
                modify = "1";
            }
            else {
                setparam = arr[i].split('=')[1];
            }
            returnurl = returnurl + arr[i].split('=')[0] + "=" + setparam + "&";
        }

        returnurl = returnurl.substr(0, returnurl.length - 1);

        if (modify == "0")
            if (returnurl == str)
                returnurl = returnurl + "&" + ref + "=" + value;
    }
    else {
        if (str.indexOf('=') != -1) {
            arr = str.split('=');

            if (arr[0] == ref) {
                setparam = value;
                modify = "1";
            }
            else {
                setparam = arr[1];
            }
            returnurl = arr[0] + "=" + setparam;
            if (modify == "0")
                if (returnurl == str)
                    returnurl = returnurl + "&" + ref + "=" + value;
        }
        else
            returnurl = ref + "=" + value;
    }
    return url.substr(0, url.indexOf('?')) + "?" + returnurl;
}

function delQueStr(url, ref) {
    var str = "";
    if (url.indexOf('?') != -1) {
        str = url.substr(url.indexOf('?') + 1);
    }
    else {
        return url;
    }
    var arr = "";
    var returnurl = "";
    var setparam = "";
    if (str.indexOf('&') != -1) {
        arr = str.split('&');
        for (i in arr) {
            if (arr[i].split('=')[0] != ref) {
                returnurl = returnurl + arr[i].split('=')[0] + "=" + arr[i].split('=')[1] + "&";
            }
        }
        return url.substr(0, url.indexOf('?')) + "?" + returnurl.substr(0, returnurl.length - 1);
    }
    else {
        arr = str.split('=');
        if (arr[0] == ref) {
            return url.substr(0, url.indexOf('?'));
        }
        else {
            return url;
        }
    }
}

//alert('rec:'+GetQueryString('rec'));
function addcookie(name,value,expireHours){
	var cookieString=name+"="+escape(value)+"; path=/";
	//判断是否设置过期时间
	if(expireHours>0){
		var date=new Date();
		date.setTime(date.getTime+expireHours*3600*1000);
		cookieString=cookieString+"; expire="+date.toGMTString();
	}
	document.cookie=cookieString;
}

function getcookie(name){
	var strcookie=document.cookie;
	var arrcookie=strcookie.split("; ");
	for(var i=0;i<arrcookie.length;i++){
	var arr=arrcookie[i].split("=");
	if(arr[0]==name)return arr[1];
	}
	return "";
}

function delCookie(name){//删除cookie
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval=getcookie(name);
	if(cval!=null) document.cookie= name + "="+cval+"; path=/;expires="+exp.toGMTString();
}


/**
 * 时间转换
 * @param timestamp
 * @returns {string}
 */
function getLocalTime(timestamp) {
    var d = new Date(parseInt(timestamp) * 1000);
    var s = '';
    s += d.getFullYear() + '年';
    s += (d.getMonth() + 1) + '月';
    s += d.getDate() + '日';
    s += d.getHours() + ':';
    s += d.getMinutes();
    return s;
}
/**
 * 时间转换
 * @param timestamp
 * @returns {string}
 */
function getLocalDate(timestamp) {
    var d = new Date(parseInt(timestamp) * 1000);
    var s = '';
    s += d.getFullYear() + '年';
    s += (d.getMonth() + 1) + '月';
    s += d.getDate() + '日';
    return s;
}

function get_encode_url(){
    return encodeURIComponent(location.href.split('#')[0]);
}

function checklogin(state){
	if(state == 0){
		//location.href = WapSiteUrl+'/tmpl/member/login.html';
		wxLogin();
		//location.href = referurl;
		return false;
	}else {
		return true;
	}
}

function contains(arr, str) {
    var i = arr.length;
    while (i--) {
           if (arr[i] === str) {
           return true;
           }
    }
    return false;
}

function buildUrl(type, data) {
    var url = WapSiteUrl;
    switch (type) {
        case 'keyword':
            url = WapSiteUrl + '/tmpl/product_list.html?keyword=' + encodeURIComponent(data);break;
        case 'special':
            url = WapSiteUrl + '/special.html?special_id=' + data;break;
        case 'goods':
            url = WapSiteUrl + '/tmpl/product_detail.html?goods_id=' + data;break;
        case 'url':
            return data;
    }

    return bindParam2Url(url);
}

//绑定一些自定义参数到url中
function bindParam2Url(url){
    if(url.indexOf('javascript:') != -1){
        return url;
    }

    var rec=GetQueryString('rec');
    if(rec!=null){
        url= changeURLParam(url,'rec',rec);
    }else{
    //alert('您这个链接不是通过分享链接进来，可能会没有红包优惠哦。');
    }
    return url;
}
//页面跳转
function wx_redirect(url){
    window.location.href = bindParam2Url(url);
}
//为超链接href属性绑定一些参数
function bind_redirect(obj){
    if($(obj).attr('href').indexOf('javascript:') == -1){
        $(obj).attr('href',bindParam2Url($(obj).attr('href')));
    }
    return true;
}
//为超链接绑定事件
function bind4ChangHref(){
    $('a').on('click',function(){
        return bind_redirect(this);
    });
}

function wxLogin(){
	/*delCookie('username');
	delCookie('key');*/
	 /*delCookie(xID);*/
	//alert('wxlogin:hello');
	$.ajax({
		type:'post',
		url:ApiUrl+WxLoginUrl,//+'&is_browser=1',
		//data:{username:username,password:pwd,client:client},
		dataType:'json',
		success:function(result){
			//alert('login_result');
			if(!result.datas.error){
				if(typeof(result.datas.key)=='undefined'){
					return false;
				}else{
					//addcookie('username',result.datas.username);
					//addcookie('key',result.datas.key);
					//location.href = referurl;
					$.each(result.datas,function(i,v){
                        addcookie(i,v);
					 });
				}
				$(".error-tips").hide();
			}else{
				$(".error-tips").html(result.datas.error).show();
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){

			//如果出错跳转到登陆处理程序
			location.href = bindParam2Url(ApiUrl+WxLoginUrl+'&login_redirect_url='+get_encode_url());
		},
		async:false
	});
}

function loginCheck(){
	var key = getcookie('key');
	if(key==''){
		wxLogin();
	}else{
        $.ajax({
            type:'get',
            url:ApiUrl+loginStatus,
            dataType:'json',
            success:function(result){
                if(result.datas.status==2){
                    delCookie('key');
                    wxLogin();
                }
            }
        });
    }
}
function wxJsSdk(){
    //appId = getcookie('appId');
    //if(appId==''){
        $.ajax({
            type:'post',
            url:ApiUrl+WxJsSdkUrl,
            data:{url:encodeURIComponent(location.href.split('#')[0]),url2:location.href},
            dataType:'json',
            success:function(result){
                if(!result.datas.error){
                    if(typeof(result.datas)=='undefined'){
                        return false;
                    }else{
                        //signPackage = result.datas.signPackage;

                        //addcookie('signPackage',signPackage);
                        //location.href = referurl;
                        $.each(result.datas.signPackage,function(i,v){
                            addcookie(i,v);
                         });
                    }
                    $(".error-tips").hide();
                }else{
                    $(".error-tips").html(result.datas.error).show();
                }
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){

                //如果出错跳转到登陆处理程序
                // location.href = ApiUrl+WxLoginUrl+'&login_redirect=1';
            },
            async:false
        });
    //}

}
loginCheck();
//wxLogin();
